<template>
	<view class="container">
		<!-- 触发按钮 -->
		<button @click="showMediaPicker">选择媒体文件</button>

		<!-- 自定义弹窗 -->
		<media-picker ref="mediaPicker" @select="handleFileSelect" />

		<!-- 预览区域 -->
		<view class="file-list">
			<view v-for="(file, index) in fileList" :key="index" class="preview">
				<image v-if="file.type === 'image'" :src="file.path" mode="aspectFit"></image>
				<video v-else :src="file.path" controls></video>
				<view class="file-info">
					<text>文件名：{{ file.name }}</text>
					<text>文件类型：{{ file.type }}</text>
					<text>文件大小：{{ formatSize(file.size) }}</text>
					<text>MD5值：<text class="md5">{{ file.md5 || '计算中...' }}</text></text>
				</view>
			</view>
		</view>

	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import MediaPicker from '@/components/MediaPicker/MediaPicker.vue'
import SparkMD5 from 'spark-md5'

const mediaPopup = ref(null)
const selectedFile = ref(null)
const mediaPicker = ref(null)
const fileList = ref([])
// 是否图片类型
const isImage = computed(() => {
	return selectedFile.value?.type === 'image'
})

// 显示选择器
const showMediaPicker = async () => {
	// 检查权限
	// #ifdef APP
	const hasPermission = await checkStoragePermission()
	if (!hasPermission) return
	// #endif
	

	mediaPicker.value.open()
}

// 检查存储权限
const checkStoragePermission = async () => {
	try {
		const status = await new Promise((resolve) => {
			plus.android.requestPermissions(
				['android.permission.READ_EXTERNAL_STORAGE'],
				(result) => resolve(result.granted.length > 0),
				(error) => resolve(false)
			)
		})

		if (!status) {
			uni.showModal({
				title: '权限提示',
				content: '需要存储权限才能选择文件',
				confirmText: '去设置',
				success: (res) => {
					if (res.confirm) plus.runtime.openSettings()
				}
			})
		}
		return status
	} catch (error) {
		console.error('权限检查失败:', error)
		return false
	}
}

// 处理文件选择
const handleFileSelect = async (files) => {
  if (files && files.length > 0) {
    // 处理每个选中的文件
    for (const file of files) {
      const newFile = {
        ...file,
		file:file,
        md5: null
      }
      fileList.value.push(newFile)

      try {
		console.log(file)
        const md5 = await calculateMd5(file)
		fileList.value[fileList.value.length-1].md5 = md5
		console.log("md5", md5)

        // 1.更新对应文件的 md5
		newFile.md5 = md5

      } catch (error) {
        console.error('MD5计算失败:', error)
        uni.showToast({
          title: 'MD5计算失败',
          icon: 'none'
        })
      }
    }
  }
}

// 计算MD5
const calculateMd5 = async (file) => {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    const spark = new SparkMD5.ArrayBuffer()
    const reader = new FileReader()
    reader.readAsArrayBuffer(file.file || new Blob([file]))
    reader.onload = (e) => {
      spark.append(e.target.result)
      const md5 = spark.end()
      resolve(md5)
    }
    reader.onerror = (error) => {
      reject(new Error('文件读取失败'))
    }
    // #endif

    // #ifdef APP-PLUS
    // 确保使用正确的文件路径
    const filePath = file.path || file.url
    if (!filePath) {
      reject(new Error('文件路径无效'))
      return
    }

    plus.io.getFileInfo({
      filePath: filePath,
      digestAlgorithm: "md5",
      success: function(e) {
        if (e && e.digest) {
          resolve(e.digest)
        } else {
          reject(new Error('MD5计算失败'))
        }
      },
      fail: function(e) {
        console.error('获取文件信息失败：', e)
        reject(new Error('获取文件信息失败'))
      }
    })
    // #endif
  })
}
// 错误处理
const handleError = (error) => {
	console.error('选择文件失败:', error)
	uni.showToast({
		title: '选择文件失败',
		icon: 'none'
	})
}

// 工具方法：格式化文件大小
const formatSize = (bytes) => {
	if (!bytes) return '0 B'
	const units = ['B', 'KB', 'MB', 'GB']
	let unitIndex = 0
	while (bytes >= 1024 && unitIndex < units.length - 1) {
		bytes /= 1024
		unitIndex++
	}
	return `${bytes.toFixed(2)} ${units[unitIndex]}`
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
}
.s-page{
  height: 100vh;
  display: flex;
  padding: 20rpx;
  flex-direction: column;
//   .file-list{
//     flex: 1;
//   }
}

.file-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-top: 40rpx;
}

.media-picker {
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding: 40rpx;

	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;

		.title {
			font-size: 36rpx;
			font-weight: bold;
		}

		.close {
			font-size: 50rpx;
			color: #999;
		}
	}

	.options {
		display: flex;
		justify-content: space-around;

		.option-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx;
			border-radius: 16rpx;
			width: 200rpx;
			border: 2rpx solid #eee;

			text {
				margin-top: 16rpx;
				font-size: 28rpx;
			}
		}
	}
}

.preview {
	margin-top: 40rpx;

	image,
	video {
		width: 100%;
		height: 400rpx;
		background: #f5f7fa;
		border-radius: 16rpx;
	}

	.file-info {
		margin-top: 20rpx;
		padding: 20rpx;
		background: #f5f7fa;
		border-radius: 12rpx;

		text {
			display: block;
			margin: 10rpx 0;
			font-size: 28rpx;
			color: #666;
		}
	}
}

.file-info {

	.md5 {
		color: #67c23a;
		font-family: monospace;
	}
}
</style>